﻿using System.Drawing;
using System.IO;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;

namespace HuiLian.Common.Helper
{
    public class QRCodeHelper
    {
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="context">二维码内容</param>
        /// <param name="imgpath">二维码图片</param>
        /// <param name="width">二维码宽</param>
        /// <param name="height">二维码高</param>
        /// <returns>图片</returns>
        public static Bitmap GetQRCode(string context, string imgpath, int width, int height)
        {
            if (width < 1 || height < 1 || string.IsNullOrEmpty(context))
            {
                throw new IOException("context is null or size is wrong!");
            }
            Bitmap origin = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions
                {
                    Width = width,
                    Height = height,
                    Margin = 1,
                }
            }.Write(context);
            if (File.Exists(imgpath))
            {
                Bitmap icoimg = new Bitmap(imgpath);
                Bitmap result = new Bitmap(width, height);
                using (Graphics graphics = Graphics.FromImage(result))
                {
                    graphics.DrawImage(origin, 0, 0, result.Width, result.Height);
                    int x = (result.Width - icoimg.Width) / 2;
                    int y = (result.Height - icoimg.Height) / 2;
                    graphics.DrawImage(icoimg, x, y, icoimg.Width, icoimg.Height);
                }
                return result;
            }
            return origin;
        }

        /// <summary>
        /// 生成条码图片
        /// </summary>
        /// <param name="context">条码内容</param>
        /// <param name="width">条码宽</param>
        /// <param name="height">条码高</param>
        /// <param name="pureBarcode">是否显示内容，false显示，true不显示</param>
        /// <returns>图片</returns>
        public static Bitmap GetBarCode(string context, int width, int height, bool pureBarcode)
        {
            if (width < 1 || height < 1 || string.IsNullOrEmpty(context))
            {
                throw new IOException("context is null or size is wrong!");
            }
            Bitmap result = new BarcodeWriter
            {
                Format = BarcodeFormat.CODE_128,
                Options = new EncodingOptions
                {
                    Width = width,
                    Height = height,
                    Margin = 0,
                    PureBarcode = pureBarcode,
                }
            }.Write(context);
            return result;
        }

    }
}
